<template>
  <div class="main-container">
    <!-- 顶部导航 -->
    <AppHeader 
      @menu-action="handleMenuAction" 
      @file-upload="handleFileUpload"
    />

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 左侧操作区 -->
      <div class="left-sidebar">
        <!-- 自动检测 -->
        <div class="sidebar-section">
          <el-button 
            class="auto-detect-btn"
            :disabled="!analysisStore.currentImage"
            @click="handleAutoDetect"
          >
            自动检测
          </el-button>
        </div>

        <!-- 结果选择 -->
        <div class="sidebar-section">
          <h3 class="section-title">结果</h3>
          <el-select 
            v-model="selectedResult" 
            placeholder="请选择"
            class="result-select"
          >
            <el-option label="T2" value="T2" />
            <el-option label="L1" value="L1" />
            <el-option label="L2" value="L2" />
          </el-select>
        </div>

        <!-- 手动定位 -->
        <div class="sidebar-section">
          <h3 class="section-title">手动定位</h3>
          <div class="manual-buttons">
            <el-button 
              :type="selectedPosition === 'T2' ? 'primary' : 'default'"
              class="manual-btn"
              @click="selectedPosition = 'T2'"
            >
              T2
            </el-button>
            <el-button 
              :type="selectedPosition === 'L1' ? 'primary' : 'default'"
              class="manual-btn"
              @click="selectedPosition = 'L1'"
            >
              L1
            </el-button>
            <el-button 
              :type="selectedPosition === 'L2' ? 'primary' : 'default'"
              class="manual-btn"
              @click="selectedPosition = 'L2'"
            >
              L2
            </el-button>
          </div>
        </div>

        <!-- 手动标记 -->
        <div class="sidebar-section">
          <h3 class="section-title">手动标记</h3>
          <div class="manual-buttons">
            <el-button 
              :type="selectedMark === 'T2' ? 'primary' : 'default'"
              class="manual-btn"
              @click="selectedMark = 'T2'"
            >
              T2
            </el-button>
            <el-button 
              :type="selectedMark === 'L1' ? 'primary' : 'default'"
              class="manual-btn"
              @click="selectedMark = 'L1'"
            >
              L1
            </el-button>
            <el-button 
              :type="selectedMark === 'L2' ? 'primary' : 'default'"
              class="manual-btn"
              @click="selectedMark = 'L2'"
            >
              L2
            </el-button>
          </div>
        </div>

        <!-- 结果打印 -->
        <div class="sidebar-section print-section">
          <el-button type="primary" class="print-btn" @click="handlePrint">
            结果打印
          </el-button>
        </div>
      </div>

      <!-- 中间影像展示区 -->
      <div class="center-viewer">
        <div class="viewer-header">
          <h2 class="viewer-title">
            <el-icon><Picture /></el-icon>
            影像显示区
          </h2>
          <div class="viewer-tools" v-if="analysisStore.currentImage">
            <el-button-group>
              <el-button :icon="ZoomIn" size="small">放大</el-button>
              <el-button :icon="ZoomOut" size="small">缩小</el-button>
              <el-button :icon="RefreshRight" size="small">重置</el-button>
            </el-button-group>
          </div>
        </div>

        <div class="viewer-content">
          <!-- 文件上传区 -->
          <div v-if="!analysisStore.currentImage" class="upload-wrapper">
            <FileUploader
              @upload-success="handleFileUploadSuccess"
              @file-change="handleFileChange"
            />
          </div>

          <!-- 影像显示 - 三视图 -->
          <div v-else class="image-display-grid">
            <!-- 冠状位 -->
            <div class="view-panel">
              <div class="view-title">检测结果</div>
              <el-image
                :src="analysisStore.currentImage.images?.coronal"
                fit="contain"
                class="ct-image"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon :size="40"><PictureFilled /></el-icon>
                    <p>影像加载失败</p>
                  </div>
                </template>
              </el-image>
            </div>

            <!-- 矢状位 -->
            <div class="view-panel">
              <div class="view-title">检测结果</div>
              <el-image
                :src="analysisStore.currentImage.images?.sagittal"
                fit="contain"
                class="ct-image"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon :size="40"><PictureFilled /></el-icon>
                    <p>影像加载失败</p>
                  </div>
                </template>
              </el-image>
            </div>

            <!-- 轴位 -->
            <div class="view-panel">
              <div class="view-title">检测结果</div>
              <el-image
                :src="analysisStore.currentImage.images?.axial"
                fit="contain"
                class="ct-image"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon :size="40"><PictureFilled /></el-icon>
                    <p>影像加载失败</p>
                  </div>
                </template>
              </el-image>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧信息栏 -->
      <div class="right-panel">
        <!-- 基本信息 -->
        <div class="panel-section">
          <h3 class="section-title">基本信息</h3>
          <div class="info-grid">
            <div class="info-row">
              <span class="info-label">ID</span>
              <span class="info-value">{{ patientInfo.id || '-' }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">姓名</span>
              <span class="info-value">{{ patientInfo.name || '-' }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">性别</span>
              <span class="info-value">{{ patientInfo.gender || '-' }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">年龄</span>
              <span class="info-value">{{ patientInfo.age || '-' }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">身高</span>
              <div class="input-with-unit">
                <el-input 
                  v-model="patientInfo.heightValue" 
                  placeholder="" 
                  size="small"
                  type="number"
                />
                <span class="unit">米</span>
              </div>
            </div>
            <div class="info-row">
              <span class="info-label">体重</span>
              <div class="input-with-unit">
                <el-input 
                  v-model="patientInfo.weightValue" 
                  placeholder="" 
                  size="small"
                  type="number"
                />
                <span class="unit">公斤</span>
              </div>
            </div>
            <div class="info-row">
              <span class="info-label">民族</span>
              <span class="info-value">{{ patientInfo.ethnicity || '-' }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">检查内容</span>
              <span class="info-value">{{ examInfo.content || '-' }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">扫描内容</span>
              <span class="info-value">{{ examInfo.scanContent || '-' }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">机型</span>
              <span class="info-value">{{ examInfo.device || '-' }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">扫描参数</span>
              <span class="info-value">{{ examInfo.scanParams || '-' }}</span>
            </div>
          </div>
        </div>

        <!-- 基线CT值 -->
        <div class="panel-section">
          <h3 class="section-title">基线CT值</h3>
          <div class="form-row">
            <div class="input-with-unit full-width">
              <el-input 
                v-model="ctValues.baseline" 
                placeholder="0" 
                size="small"
                type="number"
              />
              <span class="unit">Hu</span>
            </div>
          </div>
          
          <!-- 预设按钮 -->
          <div class="preset-buttons">
            <el-button 
              size="small" 
              :type="selectedWindow === 'bone' ? 'primary' : 'default'"
              class="preset-btn"
              @click="handleWindowPreset('bone', 1500, 500)"
            >
              骨窗(1500/500Hu)
            </el-button>
            <el-button 
              size="small" 
              :type="selectedWindow === 'soft' ? 'primary' : 'default'"
              class="preset-btn"
              @click="handleWindowPreset('soft', 400, 40)"
            >
              软组织窗(400/40Hu)
            </el-button>
            <el-button 
              size="small" 
              :type="selectedWindow === 'lung' ? 'primary' : 'default'"
              class="preset-btn"
              @click="handleWindowPreset('lung', 1500, -500)"
            >
              肺窗(1500/-500Hu)
            </el-button>
          </div>

          <!-- 窗宽窗位 -->
          <div class="form-row">
            <span class="form-label">窗宽：</span>
            <div class="input-with-unit">
              <el-input 
                v-model="ctValues.windowWidth" 
                placeholder="500" 
                size="small"
                type="number"
              />
              <span class="unit">Hu</span>
            </div>
          </div>
          <div class="form-row">
            <span class="form-label">窗位：</span>
            <div class="input-with-unit">
              <el-input 
                v-model="ctValues.windowLevel" 
                placeholder="50" 
                size="small"
                type="number"
              />
              <span class="unit">Hu</span>
            </div>
          </div>

          <!-- 自定义按钮 -->
          <el-button size="small" class="custom-btn">设置自定义窗宽窗位</el-button>
        </div>
      </div>
    </div>

    <!-- 扫描类型选择弹窗 -->
    <ScanTypeDialog
      v-model:visible="showScanTypeDialog"
      :default-type="analysisStore.scanType"
      :default-level="analysisStore.vertebralLevel"
      @confirm="handleScanTypeConfirm"
    />

    <!-- 检测报告弹窗 -->
    <ReportDialog
      v-model:visible="showReportDialog"
    />

    <!-- 加载成功提示 -->
    <LoadSuccessDialog
      v-model:visible="showLoadSuccessDialog"
      :file-info="loadedFileInfo"
      @start-analysis="handleQuickStartAnalysis"
    />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Upload,
  VideoPlay,
  Document,
  Download,
  Picture,
  PictureFilled,
  ZoomIn,
  ZoomOut,
  RefreshRight
} from '@element-plus/icons-vue'
import AppHeader from '@/components/layout/AppHeader.vue'
import FileUploader from '@/components/business/FileUploader.vue'
import ScanTypeDialog from '@/components/dialog/ScanTypeDialog.vue'
import ReportDialog from '@/components/dialog/ReportDialog.vue'
import LoadSuccessDialog from '@/components/dialog/LoadSuccessDialog.vue'
import { useAnalysisStore } from '@/stores/analysis'

const analysisStore = useAnalysisStore()

// 弹窗控制
const showScanTypeDialog = ref(false)
const showReportDialog = ref(false)
const showLoadSuccessDialog = ref(false)
const loadedFileInfo = ref({})

// 选择的结果
const selectedResult = ref('T2')
const selectedPosition = ref('')  // 手动定位选中状态
const selectedMark = ref('')      // 手动标记选中状态

// 患者信息
const patientInfo = ref({
  id: 'P001234',
  name: '张三',
  gender: '男',
  age: '45',
  heightValue: '',
  weightValue: '',
  ethnicity: '汉族'
})

// 检查信息
const examInfo = ref({
  content: '腹部CT平扫',
  scanContent: '全腹部扫描',
  device: 'GE Revolution CT',
  scanParams: 'kV:120, mA:200, 层厚:5mm'
})

// CT值设置
const ctValues = ref({
  baseline: '0',
  windowWidth: '500',
  windowLevel: '50'
})
const selectedWindow = ref('')  // 预设窗选中状态

// 自动检测
const handleAutoDetect = () => {
  if (!analysisStore.currentImage) {
    ElMessage.warning('请先加载文件')
    return
  }
  handleStartAnalysis()
}

// 文件上传（从顶部导航栏）
const handleFileUpload = (file) => {
  if (!file) return
  
  // 模拟文件上传和处理
  const fileInfo = {
    name: file.name,
    size: file.size,
    uploadTime: new Date().toLocaleString('zh-CN'),
    images: {
      coronal: new URL('@/img/ct1.png', import.meta.url).href,
      sagittal: new URL('@/img/ct2.png', import.meta.url).href,
      axial: new URL('@/img/ct3.png', import.meta.url).href
    }
  }
  
  // 保存到 store
  analysisStore.currentImage = fileInfo
  
  ElMessage.success(`文件 ${file.name} 加载成功`)
}

const handleUploadClick = () => {
  // 触发文件选择（通过 FileUploader 组件）
  ElMessage.info('请在下方区域选择或拖拽文件')
}

const handleFileUploadSuccess = (fileInfo) => {
  loadedFileInfo.value = fileInfo
  showLoadSuccessDialog.value = true
}

const handleFileChange = async (fileInfo) => {
  // 保存完整的文件信息（包括三视图）
  analysisStore.currentImage = {
    name: fileInfo.name,
    size: fileInfo.size,
    uploadTime: fileInfo.uploadTime,
    images: fileInfo.images
  }
  ElMessage.success('文件加载成功')
}

// 开始分析
const handleStartAnalysis = async () => {
  if (!analysisStore.currentImage) {
    ElMessage.warning('请先加载文件')
    return
  }

  try {
    await analysisStore.startAnalysis()
    ElMessage.success('分析完成！')
    showReportDialog.value = true
  } catch (error) {
    ElMessage.error('分析失败，请重试')
  }
}

const handleQuickStartAnalysis = () => {
  handleStartAnalysis()
}

// 顶部菜单操作
const handleMenuAction = (action) => {
  switch(action) {
    case 'file':
      ElMessage.info('文件菜单')
      break
    case 'view':
      ElMessage.info('视图菜单')
      break
    case 'history':
      ElMessage.info('历史记录')
      break
    case 'scan-type':
      showScanTypeDialog.value = true
      break
    case 'report':
      showReportDialog.value = true
      break
  }
}

// 扫描类型确认
const handleScanTypeConfirm = (data) => {
  analysisStore.setScanType(data.scanType)
  ElMessage.success('参数设置成功')
}

// 参数变更
const handleScanTypeChange = () => {
  ElMessage.info('扫描类型已更新')
}

const handleVertebralLevelChange = () => {
  ElMessage.info('椎体层面已更新')
}

const handleDisplayOptionChange = () => {
  // 更新显示选项
}

// 导出
const handleExport = () => {
  if (!analysisStore.analysisResult) {
    ElMessage.warning('暂无分析结果')
    return
  }
  
  ElMessage.success('正在导出结果...')
  // 实际项目中这里应该调用导出API
}

const handleExportReport = (reportData) => {
  ElMessage.success('正在导出PDF报告...')
  // 实际项目中这里应该调用PDF生成API
}

const handlePrint = () => {
  if (!analysisStore.analysisResult) {
    ElMessage.warning('暂无分析结果')
    return
  }
  
  ElMessage.success('正在打印结果...')
  // 实际项目中这里应该调用打印API
}

// 窗口预设处理
const handleWindowPreset = (type, width, level) => {
  selectedWindow.value = type
  ctValues.value.windowWidth = width.toString()
  ctValues.value.windowLevel = level.toString()
  ElMessage.success(`已应用${type === 'bone' ? '骨窗' : type === 'soft' ? '软组织窗' : '肺窗'}参数`)
}

const getRiskTagType = (risk) => {
  const riskMap = {
    '低': 'success',
    '中等': 'warning',
    '高': 'danger'
  }
  return riskMap[risk] || 'info'
}
</script>

<style lang="scss" scoped>
.main-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--bg-gradient);
  box-sizing: border-box;

  .main-content {
    flex: 1;
    display: flex;
    gap: var(--spacing-md);
    padding: var(--spacing-md);
    height: calc(100vh - 60px);
    overflow: hidden;
    box-sizing: border-box;

    // 左侧操作区 - 卡片化设计
    .left-sidebar {
      width: 260px;
      background: var(--bg-card);
      border-radius: var(--radius-xl);
      box-shadow: var(--shadow-card);
      overflow-y: auto;
      padding: var(--spacing-lg);
      display: flex;
      flex-direction: column;
      box-sizing: border-box;
      transition: all var(--transition-base);

      // 统一处理所有按钮样式 - 新风格
      .el-button {
        width: 100%;
        height: 40px;
        font-size: 14px;
        border-radius: var(--radius-sm);
        transition: all var(--transition-base);
        margin: 0 !important;
        padding: 0 var(--spacing-md) !important;
        box-sizing: border-box;
        font-weight: 500;

        &:hover {
          transform: translateY(-2px);
          box-shadow: var(--shadow-md);
        }
        
        &.is-type-primary {
          background: linear-gradient(135deg, var(--color-primary) 0%, var(--color-primary-light) 100%);
          border: none;
          color: white;
        }
      }

      // 统一处理所有选择框
      .el-select {
        width: 100%;
        
        :deep(.el-input__wrapper) {
          border-radius: 6px;
        }
      }

      .sidebar-section {
        margin-bottom: 20px;

        .section-title {
          font-size: 14px;
          font-weight: 600;
          color: #303133;
          margin: 0 0 14px 0;
          text-align: center;
          letter-spacing: 0.5px;
        }

        // 按钮容器统一样式
        .mode-buttons,
        .manual-buttons {
          display: flex;
          flex-direction: column;
          gap: 10px;
          margin: 0;
          padding: 0;
        }

        // 单独的按钮（如自动检测）
        > .el-button {
          margin: 0 !important;
        }

        // 打印按钮区域
        &.print-section {
          margin-top: auto;
          padding-top: 20px;
          border-top: 1px solid #dcdfe6;

          .print-btn {
            width: 100%;
            height: 40px;
            font-size: 14px;
            font-weight: 500;
            border-radius: 6px;
            transition: all 0.3s ease;

            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
            }
          }
        }
      }
    }

    // 中间影像区 - 卡片化设计
    .center-viewer {
      flex: 1;
      display: flex;
      flex-direction: column;
      background: var(--bg-card);
      border-radius: var(--radius-xl);
      box-shadow: var(--shadow-card);
      overflow: hidden;

      .viewer-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 16px 20px;
        border-bottom: 1px solid #e4e7ed;

        .viewer-title {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
      }

      .viewer-content {
        flex: 1;
        position: relative;
        overflow: hidden;

        .upload-wrapper {
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 40px;
        }

        .image-display-grid {
          height: 100%;
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 0;
          background: #000000;

          .view-panel {
            position: relative;
            display: flex;
            flex-direction: column;
            border-right: 1px solid #333;

            &:last-child {
              border-right: none;
            }

            .view-title {
              position: absolute;
              top: 10px;
              left: 50%;
              transform: translateX(-50%);
              color: #ffffff;
              font-size: 14px;
              font-weight: 500;
              z-index: 10;
              background: rgba(0, 0, 0, 0.6);
              padding: 4px 12px;
              border-radius: 4px;
              letter-spacing: 0.5px;
            }

            .ct-image {
              width: 100%;
              height: 100%;
              display: flex;
              align-items: center;
              justify-content: center;

              :deep(img) {
                max-width: 100%;
                max-height: 100%;
                object-fit: contain;
              }

              .image-error {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                height: 100%;
                color: #666;
                gap: 12px;
                font-size: 13px;
              }
            }
          }
        }
      }
    }

    // 右侧信息栏 - 卡片化设计
    .right-panel {
      width: 340px;
      background: var(--bg-card);
      border-radius: var(--radius-xl);
      box-shadow: var(--shadow-card);
      overflow-y: auto;
      padding: var(--spacing-lg);

      .panel-section {
        margin-bottom: var(--spacing-lg);
        padding: var(--spacing-md);
        background: var(--color-divider);
        border-radius: 8px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);

        &:last-child {
          margin-bottom: 0;
        }

        .section-title {
          font-size: 14px;
          font-weight: 600;
          color: #303133;
          margin-bottom: 14px;
          text-align: center;
          letter-spacing: 0.5px;
        }

        .info-grid {
          display: grid;
          grid-template-columns: auto 1fr;
          gap: 10px 16px;
          align-items: center;
        }

        .info-row {
          display: contents;

          .info-label {
            font-size: 13px;
            color: #606266;
            font-weight: 500;
            text-align: left;
            white-space: nowrap;
          }

          .info-value {
            font-size: 13px;
            color: #303133;
            text-align: left;
          }

          .input-with-unit {
            display: flex;
            align-items: center;
            gap: 6px;

            &.full-width {
              width: 100%;
            }

            .el-input {
              flex: 1;
            }

            .unit {
              font-size: 13px;
              color: #606266;
              white-space: nowrap;
              min-width: 30px;
            }
          }
        }

        .info-value-simple {
          font-size: 13px;
          color: #606266;
          line-height: 1.6;
        }

        .form-row {
          display: flex;
          align-items: center;
          gap: 8px;

          .form-label {
            min-width: 40px;
            font-size: 13px;
            color: #606266;
            font-weight: 500;
          }

          .input-with-unit {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 6px;

            &.full-width {
              width: 100%;
            }

            .el-input {
              flex: 1;
            }

            .unit {
              font-size: 13px;
              color: #606266;
              white-space: nowrap;
              min-width: 30px;
            }
          }
        }

        .preset-buttons {
          display: flex;
          flex-direction: column;
          gap: 10px;
          margin: 14px 0;

          .el-button {
            width: 100%;
            font-size: 13px;
            height: 36px;
            margin: 0 !important;
            padding: 0 12px !important;
            box-sizing: border-box;
            transition: all 0.3s ease;

            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 4px 8px rgba(0, 0, 0, 0.12);
            }
          }
        }

        .custom-btn {
          width: 100%;
          margin: 12px 0 0 0 !important;
          font-size: 13px;
          height: 36px;
          padding: 0 12px !important;
          box-sizing: border-box;
          
          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.12);
          }
        }

        .result-grid {
          display: flex;
          flex-direction: column;
          gap: 12px;

          .result-item {
            padding: 12px;
            background: #f9fafc;
            border-radius: 6px;
            border-left: 3px solid #409EFF;

            .result-label {
              font-size: 12px;
              color: #909399;
              margin-bottom: 6px;
            }

            .result-value {
              font-size: 16px;
              font-weight: 600;
              color: #409EFF;
            }
          }
        }

        .risk-grid {
          display: flex;
          flex-direction: column;
          gap: 12px;

          .risk-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 12px;
            background: #f9fafc;
            border-radius: 6px;

            .risk-label {
              font-size: 13px;
              color: #606266;
              font-weight: 500;
            }
          }
        }
      }
    }
  }
}

// 响应式
@media (max-width: 1440px) {
  .main-content {
    .left-sidebar {
      width: 200px;
      padding: 16px 12px;
    }

    .right-panel {
      width: 300px;
      padding: 16px 12px;
    }
  }
}

@media (max-width: 1200px) {
  .main-content {
    .left-sidebar {
      width: 180px;
      padding: 12px 8px;
      
      .sidebar-section {
        margin-bottom: 16px;
        
        .section-title {
          font-size: 13px;
          margin-bottom: 10px;
        }
        
        .mode-btn,
        .auto-detect-btn,
        .manual-btn,
        .action-btn {
          height: 34px;
          font-size: 13px;
        }
      }
    }
  }
}
</style>

